package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"life-ease/cache"
	"life-ease/models"
	"life-ease/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")
	var login models.User
	err := models.DB.Where("username = ?", username).First(&login).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5str(password) != login.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	cate := c.PostForm("cate")
	if title == "" || content == "" || cate == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	add := models.Life{
		Title:   title,
		Content: content,
		Cate:    cate,
	}
	err := models.DB.Create(&add).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "life_add" + strconv.Itoa(int(add.ID))
	var news models.Life
	models.DB.Where("id = ?", add.ID).First(&news)
	jsonAdd, _ := json.Marshal(news)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonAdd, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Life
	models.DB.Where("id = ?", id).First(&detail)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": detail,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Delete(&models.Life{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "life_del" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var list []models.Life
	redis_key := "life_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
